package com.qcby.community.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qcby.community.annotation.LogAnnotation;
import com.qcby.community.configuration.ApiConfiguration;
import com.qcby.community.entity.Community;
import com.qcby.community.entity.InOutRecord;
import com.qcby.community.entity.Person;
import com.qcby.community.form.InOutFaceForm;
import com.qcby.community.form.InOutQueryForm;
import com.qcby.community.mapper.InOutRecordMapper;
import com.qcby.community.service.CommunityService;
import com.qcby.community.service.InOutRecordService;
import com.qcby.community.service.PersonService;
import com.qcby.community.util.Base64Util;
import com.qcby.community.util.FaceApi;
import com.qcby.community.util.Result;
import com.qcby.community.util.RootResp;
import com.qcby.community.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-03-25
 */
@RestController
@RequestMapping("/sys/inOut")
public class InOutRecordController {

    @Autowired
    private InOutRecordService inOutRecordService;

    @Autowired
    private CommunityService communityService;

    @Autowired
    private ApiConfiguration apiConfiguration;

    @Autowired
    private PersonService personService;

    @Autowired
    private InOutRecordMapper inOutRecordMapper;

    @Value("${upload.face}")
    private String face;

    @Value("${upload.urlPrefix}")
    private String urlPrefix;

    /**
     * 数据统计柱状图
     * @return
     */
    @GetMapping("/chart")
    public Result chart(){
        Map map = this.inOutRecordService.chart();
        return Result.ok().put("data",map);
    }

    /**
     * 出入记录查询
     * @param inOutQueryForm
     * @return
     */
    @GetMapping("/list")
    public Result list(InOutQueryForm inOutQueryForm){
        PageVO pageVO = this.inOutRecordService.inoutList(inOutQueryForm);
        Map map = new HashMap();
        map.put("pageList",pageVO);
        return Result.ok().put("data",map);
    }

    /**
     * 人脸识别---加载小区数据
     * @return
     */
    @GetMapping("/communityList")
    public Result communityList(){
        List<Community> list = this.communityService.list();
        if(list == null){
            return Result.error("没有小区数据");
        }
        return Result.ok().put("data",list);
    }

    /**
     * 人脸识别
     * @param inOutFaceForm
     * @return
     */
    @LogAnnotation("人脸识别")
    @PostMapping("/add")
    public Result add(@RequestBody InOutFaceForm inOutFaceForm){
//        //第一种方式
//        //模拟人脸识别
//        String fileBase64 = inOutFaceForm.getFileBase64();
//        String faceBase = fileBase64.substring(0,60);
//        //如果不是头像
//        if(faceBase.equals("iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAAAXNSR0IArs4c")){
//            return Result.ok().put("status","fail").put("data","人脸识别失败");
//        }
//        QueryWrapper<Person> personQueryWrapper = new QueryWrapper<>();
//        personQueryWrapper.eq("face_base",faceBase);
//        Person person = this.personService.getOne(personQueryWrapper);
//        if(person == null){
//            return Result.ok().put("status","fail").put("data","人员信息不存在");
//        }
//        if(inOutFaceForm.getCommunityId() != person.getCommunityId()){
//            return Result.ok().put("status","fail").put("data","对不起，你不是本小区居民，请与系统管理员联系");
//        }
//        InOutRecord inOutRecord = new InOutRecord();
//        inOutRecord.setCommunityId(person.getCommunityId());
//        inOutRecord.setPersonId(person.getPersonId());
//        try{
//            //保存图片
//            String newFileName = UUID.randomUUID() + "." +inOutFaceForm.getExtName();
//            String fileName = face + newFileName;
//            Base64Util.decoderBase64File(fileBase64,fileName);
//            String basePath = urlPrefix + "community/upload/face/" + newFileName;
//            //查找系统中是否有该人员的出入场信息
//            InOutRecord inOutRecord1 = this.inOutRecordMapper.getInOutRecord(inOutRecord);
//            //进入小区
//            if(inOutRecord1 == null){
//                inOutRecord.setInPic(basePath);
//                return Result.ok().put("status","success").put("data","【" + person.getUserName() + "】进入小区");
//            }else {
//                //离开小区
//                inOutRecord1.setOutPic(basePath);
//                this.inOutRecordMapper.updateById(inOutRecord1);
//                return Result.ok().put("status", "success").put("data", "【"+person.getUserName() + "】离开小区");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;

        //第二种方式
        //腾讯
        FaceApi faceApi = new FaceApi();
        RootResp resp = faceApi.searchPersonsReturnsByGroup(apiConfiguration,inOutFaceForm.getFileBase64());
        String msg = "";
        JSONObject personInfo = null;
        if(resp.getRet() == 0){
            JSONObject object = JSONObject.parseObject(resp.getData().toString());
            JSONArray resultsReturnsByGroup = object.getJSONArray("ResultsReturnsByGroup");
            JSONObject returnsByGroupJSONObject = resultsReturnsByGroup.getJSONObject(0);
            JSONArray groupCandidates = returnsByGroupJSONObject.getJSONArray("GroupCandidates");
            JSONObject groupCandidatesJSONObject = groupCandidates.getJSONObject(0);
            JSONArray candidates = groupCandidatesJSONObject.getJSONArray("Candidates");
            //返回多个人员，匹配数据库人员信息
            String personId = "";
            String faceId = "";
            String personName = "";
            String faceUrl = "";
            Integer pid = 0;
            Person p = null,p1 = null;
            for (int i = 0; i < candidates.size(); i++) {
                personInfo = candidates.getJSONObject(i);
                personId = personInfo.getString("PersonId");
                faceId = personInfo.getString("FaceId");
                personName = personInfo.getString("PersonName");
                personId = personId.substring(4);
                pid = Integer.parseInt(personId);
                p = personService.getById(pid);
                if(p == null){
                    continue;
                }else {
                    p1 = p;
                }
                faceUrl = p.getFaceUrl();
                if(faceUrl == null || faceUrl.equals("")){
                    continue;
                }
                faceUrl = faceUrl.substring(faceUrl.lastIndexOf("/")+1,faceUrl.lastIndexOf("."));
                if(faceId.equals(faceUrl)){
                    break;
                }
            }
            if(p == null){
                return Result.ok().put("data","人员信息不存在");
            }
            if(inOutFaceForm.getCommunityId() != p.getCommunityId()){
                return Result.ok().put("data","对不起，你不是本小区居民，请与系统管理员联系。");
            }
            InOutRecord inOutRecord = new InOutRecord();
            inOutRecord.setCommunityId(p.getCommunityId());
            inOutRecord.setPersonId(p.getPersonId());
            try {
                //保存图片
                String newFileName = UUID.randomUUID() + "." + inOutFaceForm.getExtName();
                String fileName = face + newFileName;
                Base64Util.decoderBase64File(inOutFaceForm.getFileBase64(),fileName);
                String basePath = urlPrefix + "community/upload/face/" + newFileName;
                //查找系统中是否有该人员的出入信息
                InOutRecord inOutRecord1 = this.inOutRecordMapper.getInOutRecord(inOutRecord);
                //进入小区
                if(inOutRecord1 == null){
                    inOutRecord.setInPic(basePath);
                    this.inOutRecordMapper.insert(inOutRecord);
                    return Result.ok().put("status", "success").put("data", "【"+p.getUserName() + "】进入小区");
                }else {
                    //离开小区
                    inOutRecord1.setOutPic(basePath);
                    this.inOutRecordMapper.updateById(inOutRecord1);
                    return Result.ok().put("status", "success").put("data", "【"+p.getUserName() + "】离开小区");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            msg = "人脸识别失败,错误码=" + resp.getRet() + "," + resp.getMsg();
        }
        return Result.ok().put("data","msg");
    }


}

